<?php
/***************************************************************************
 *
 *   copyright            : (C) 2011 Winds of Storm
 *
 *   $Id: index.php 132 2011-06-12 20:31:36Z stormerider $
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

require("../config.php");
$admin_header   = 1;
require($libdir . "init." . $phpEx);
require($libdir . "chat_functs." . $phpEx);
require($libdir . "admin." . $phpEx);
require($libdir . "rooms." . $phpEx);
require($libdir . "transcripts." . $phpEx);

if (isset($_REQUEST['op'])) {
    $op = strtolower($_REQUEST['op']);
} else {
    $op = '';
}

$template   = new Template($config['TPL_DIR']);
if ($op == '') {
    $sql                = "SELECT COUNT(*) AS config_count FROM {$dbprefix}config";
    $res                = $db->sql_query($sql);
    $row                = $db->sql_fetchrow($res);
    $stats['config']    = $row['config_count'];
    
    $sql                = "SELECT COUNT(user_id) AS prefs_count FROM {$dbprefix}prefs";
    $res                = $db->sql_query($sql);
    $row                = $db->sql_fetchrow($res);
    $stats['prefs']     = $row['prefs_count'];
    
    $sql                = "SELECT COUNT(room_id) AS room_count FROM {$dbprefix}rooms";
    $res                = $db->sql_query($sql);
    $row                = $db->sql_fetchrow($res);
    $stats['rooms']     = $row['room_count'];
    
    $sql                = "SELECT COUNT(event_id) AS event_count FROM {$dbprefix}events";
    $res                = $db->sql_query($sql);
    $row                = $db->sql_fetchrow($res);
    $stats['events']    = $row['event_count'];
    
    $sql                = "SELECT COUNT(alias_id) AS alias_count FROM {$dbprefix}aliases";
    $res                = $db->sql_query($sql);
    $row                = $db->sql_fetchrow($res);
    $stats['aliases']   = $row['alias_count'];
    
    $sql                = "SELECT COUNT(session_id) AS session_count FROM {$dbprefix}sessions";
    $res                = $db->sql_query($sql);
    $row                = $db->sql_fetchrow($res);
    $stats['sessions']  = $row['session_count'];
    
    foreach ($stats as $stat => $stat_value) {
        $stat_name  = ucfirst($stat);
    
        print("$stat_name table has $stat_value entries<br />");
    }
} else if (($op == 'manage_rooms') || ($op == 'del_room') || ($op == 'new_room')) {
    if ($op == 'del_room') {
        $sql    = "SELECT * FROM {$dbprefix}rooms WHERE room_id={$_REQUEST['rid']}";
        $res    = $db->sql_query($sql);
        $row    = $db->sql_fetchrow($res);
    
        $sql    = "DELETE FROM {$dbprefix}events WHERE room_id_to={$_REQUEST['rid']}";
        $res    = $db->sql_query($sql);
        $events = $db->sql_numrows($res);
        if ($events == '') {
            $events = 0;
        }

        $sql    = "DELETE FROM {$dbprefix}rooms WHERE room_id={$_REQUEST['rid']}";
        $res    = $db->sql_query($sql);
    
        $notice = "Deleted <b>" . $row['room_name'] . "</b> ($events events purged).";
    } else if ($op == 'new_room') {
        if ($_REQUEST['room_name'] != '') {
            $sql    = "INSERT INTO {$dbprefix}rooms (room_name, room_group) VALUES ('{$_REQUEST['room_name']}', {$_REQUEST['gid']})";
            $res    = $db->sql_query($sql);
    
            $notice = "Added new room '{$_REQUEST['room_name']}'.";
        } else {
            $notice = "<b>ERROR:</b> Room name may not be empty.";
        }
    }

    $template->set_filenames(array('body' => 'admin/rooms_body.tpl'));
    $template->assign_vars(array(
        'U_INDEX'   => "index.$phpEx",
    ));
    
    if ($notice != '') {
        $template->assign_block_vars('switch_notice', array('NOTICE' => $notice));
    }

    $sql    = "SELECT * FROM {$dbprefix}room_groups ORDER BY group_id";
    $res    = $db->sql_query($sql);
    while ($row = $db->sql_fetchrow($res)) {
        $vars   = array();
        while (list($k, $v) = each($row)) {
            $vars[strtoupper($k)]   = $v;
        }
        $template->assign_block_vars('groups', $vars);

        $sql    = "SELECT *
                FROM
                    {$dbprefix}rooms 
                WHERE
                    room_group={$row['group_id']}
                ORDER BY
                    room_name";
        $res2   = $db->sql_query($sql);
    
        while ($row2 = $db->sql_fetchrow($res2)) {
            $vars   = array();
            while (list($k, $v) = each($row2)) {
                $vars[strtoupper($k)]   = $v;
            }
            if ($row2['room_password'] != '') {
                $vars['PROTECTED']  = " [protected]";
            }
            if ($row2['room_limit'] != '0') {
                $vars['LIMITED']    = " [limit: {$row2['room_limit']}]";
            }
            $template->assign_block_vars('groups.rooms', $vars);
        }
    }
} else if (($op == 'manage_groups') || ($op == 'dynamic_group') || ($op == 'new_group') || ($op == 'del_group')) {
    if ($op == 'dynamic_group') {
        if ($_REQUEST['disable_dynamic'] != '') {
            $sql    = "UPDATE {$dbprefix}room_groups SET group_dynamic='no'";
            $res    = $db->sql_query($sql);
            $notice = "Disabled dynamic rooms.";
        } else {
            $sql    = "UPDATE {$dbprefix}room_groups SET group_dynamic='no' WHERE group_id={$_REQUEST['old_group_id']}";
            $res    = $db->sql_query($sql);
            $sql    = "UPDATE {$dbprefix}room_groups SET group_dynamic='yes' WHERE group_id={$_REQUEST['group_id']}";
            $res    = $db->sql_query($sql);
            $notice = "Updated the dynamic group.";
        }
    } else if ($op == 'new_group') {
        if ($_REQUEST['group_name'] != '') {
            $sql    = "INSERT INTO {$dbprefix}room_groups (group_name) VALUES ('{$_REQUEST['group_name']}')";
            $res    = $db->sql_query($sql);
            $notice = "Added group '{$_REQUEST['group_name']}'.";
        } else {
            $notice = "<b>ERROR:</b> Group name may not be empty.";
        }
    } else if ($op == 'del_group') {
        $sql    = "SELECT * FROM {$dbprefix}room_groups WHERE group_id={$_REQUEST['gid']}";
        $res    = $db->sql_query($sql);
        $row    = $db->sql_fetchrow($res);
        $sql    = "DELETE FROM {$dbprefix}room_groups WHERE group_id={$_REQUEST['gid']}";
        $res    = $db->sql_query($sql);
        $notice = "Removed group '{$row['group_name']}'.";
    }

    $template->set_filenames(array('body' => 'admin/groups_body.tpl'));
    $template->assign_vars(array(
        'U_INDEX'   => "index.$phpEx"
    ));

    if ($notice != '') {
        $template->assign_block_vars('switch_notice', array('NOTICE' => $notice));
    }

    $sql    = "SELECT * FROM {$dbprefix}room_groups ORDER BY group_id";
    $res    = $db->sql_query($sql);

    while ($row = $db->sql_fetchrow($res)) {
        $vars   = array();
        while (list($k, $v) = each($row)) {
            $vars[strtoupper($k)]   = $v;
        }
        if ($row['group_dynamic'] == 'yes') {
            $old_gid        = $row['group_id'];
            $vars['CHECKED']    = ' CHECKED';
        }
        $template->assign_block_vars('groups', $vars);
    }
    $template->assign_vars(array(
        'OLD_GROUP_ID'  => $old_gid
    ));
} else if ($op == 'edit_room') {
    $sql    = "SELECT * FROM {$dbprefix}rooms WHERE room_id={$_REQUEST['rid']}";
    $res    = $db->sql_query($sql);
    $row    = $db->sql_fetchrow($res);
    
    $template->set_filenames(array('body' => 'admin/room_edit.tpl'));
    $template->assign_vars(array(
        'ACTION'            => "index.$phpEx",
        'ROOM_ID'           => $_REQUEST['rid'],
        'ROOM_NAME'         => $row['room_name'],
        'ROOM_LIMIT'        => $row['room_limit'],
        'ROOM_PASSWORD'     => $row['room_password'],
        'ROOM_TOPIC'        => $row['room_topic'],
        'MODERATOR_GROUPS'  => showModeratorGroups($row['mod_group'])
    ));
} else if ($op == 'update_room') {

    $sql    = "UPDATE {$dbprefix}rooms
            SET
                room_name='{$_REQUEST['room_name']}',
                room_limit='{$_REQUEST['room_limit']}',
                room_password='{$_REQUEST['room_password']}',
                room_topic='{$_REQUEST['room_topic']}',
                mod_group='{$_REQUEST['mod_group']}'
            WHERE
                room_id={$_REQUEST['rid']}";
    $res    = $db->sql_query($sql);
    print("Updated {$_REQUEST['room_name']}.");
} else if ($op == 'config_plugins') {
    $template->set_filenames(array('body' => 'admin/config_plugins.tpl'));
    foreach ($plugins as $plugin) {
        if ($config[$plugin['FUNC']] == 'enabled') {
            $enabled_y  = 'CHECKED ';
            $enabled_n  = '';
        } else {
            $enabled_y  = '';
            $enabled_n  = 'CHECKED ';
        }
        $template->assign_block_vars('plugin', array(
            'NAME'          => $plugin['NAME'],
            'AUTHOR'        => $plugin['CREDIT'],
            'ID'            => $plugin['FUNC'],
            'VERSION'       => $plugin['VERSION'],
            'ENABLED_TRUE'  => $enabled_y,
            'ENABLED_FALSE' => $enabled_n,
        ));
    }
} else if ($op == 'update_plugins') {
    foreach ($plugins as $plugin) {
        $func   = $plugin['FUNC'];
        if ($config[$func] != $_REQUEST[$func]) {
            set_config($func, $_REQUEST[$func]);
            print ucfirst($_REQUEST[$func])." plugin $func.<br />\n";
        }
    }
} else if ($op == 'config_timeouts') {
    $template->set_filenames(array('body' => 'admin/config_timeouts.tpl'));
    foreach ($timeout_help as $key => $value) {
        $template->assign_block_vars('timeout', array(
            'NAME'  => $key,
            'HELP'  => $value,
            'VALUE' => $config[$key],
        ));
    }
} else if ($op == 'update_timeouts') {
    $changed    = false;
    foreach ($timeout_help as $key => $value) {
        if ($_REQUEST[$key] != $config[$key]) {
            set_config($key, $_REQUEST[$key]);
            print "Changing value of $key from {$config[$key]} to {$_REQUEST[$key]}.<br />\n";
            $changed    = true;
        }
    }
    if (!$changed) {
        print("No changes made.");
    }
} else if ($op == 'config_settings') {
    $template->set_filenames(array('body' => 'admin/config_settings.tpl'));
    foreach ($setting_help as $key => $value) {
        $cfgval = '';
        if (isset($config[$key])) {
            $cfgval = $config[$key];
        }
        $template->assign_block_vars('setting', array(
            'NAME'  => $key,
            'HELP'  => $value,
            'VALUE' => $cfgval,
        ));
    }
} else if ($op == 'update_settings') {
    $changed    = false;
    foreach ($setting_help as $key => $value) {
        if ($_REQUEST[$key] != $config[$key]) {
            if ($_REQUEST[$key] != '') {
                set_config($key, $_REQUEST[$key]);
                print "Changing value of $key from {$config[$key]} to {$_REQUEST[$key]}.<br />\n";
                $changed    = true;
            } else {
                if (isset($config[$key])) {
                    $sql    = "DELETE FROM {$dbprefix}config WHERE config_name='$key'";
                    $res    = $db2->sql_query($sql);
                }
                print "Removing $key from configuration (previous value: {$config[$key]}).<br />\n";
                $changed    = true;
            }
        }
    }
    if (!$changed) {
        print("No changes made.");
    }
} else if ($op == 'config_announce') {
    $announce    = '';
    if (isset($config['ANNOUNCEMENT'])) {
        $announce    = $config['ANNOUNCEMENT'];
    }
    $template->set_filenames(array('body' => 'admin/config_announce.tpl'));
    $template->assign_vars(array(
        'ANNOUNCEMENT' => $announce,
    ));
} else if ($op == 'update_announce') {
    $changed    = false;
    if ($_REQUEST['announcement'] != $config['ANNOUNCEMENT']) {
        if ($_REQUEST['announcement'] != '') {
            set_config('ANNOUNCEMENT', $_REQUEST['ANNOUNCEMENT']);
            print "Changing value of 'ANNOUNCEMENT' from {$config['ANNOUNCEMENT']} to {$_REQUEST['announcement']}.<br />\n";
            $changed    = true;
        } else {
            if (isset($config['ANNOUNCEMENT'])) {
                $sql    = "DELETE FROM {$dbprefix}config WHERE config_name='ANNOUNCEMENT'";
                $res    = $db2->sql_query($sql);
            }
            print "Removing 'ANNOUNCEMENT' from configuration (previous value: {$config['ANNOUNCEMENT']}).<br />\n";
            $changed    = true;
        }
    }
    if (!$changed) {
        print("No changes made.");
    }
} else if ($op == 'config_cron') {
    $template->set_filenames(array('body' => 'admin/config_cron.tpl'));
    foreach ($cron_helper as $cron) {
        $vars   = array();
        foreach ($cron as $key => $value) {
            $vars[strtoupper($key)] = $value;
        }

        if ($cron['interval'] == $config['CRON_MINUTE_INTERVAL']) {
            $vars['SELECTED']   = 'SELECTED';
        }
        $template->assign_block_vars('cron', $vars);
    }
} else if ($op == 'update_cron') {
    foreach ($cron_helper as $values) {
        if ($values['time'] == $_REQUEST['cron']) {
            $cron   = $values;
        }
    }
    if (!isset($cron)) {
        print("Error setting cron values.");
    } else {
        set_config('CRON_MINUTE_INTERVAL', $cron['interval']);
        print("Set CRON_MINUTE_INTERVAL to {$cron['name']}. You should adjust your crontab to include the following:\n<pre>");
        $path   = $basedir.'scripts';
        print("{$cron['syntax']} * * * * $path/sessions.php\n");
        print("{$cron['syntax']} * * * * $path/timers.php\n");
        print("0 0 * * * $path/transcripts.php\n");
        print("</pre>");
    }
} else if ($op == 'maint_backup') {
    $fname  = backup_tables($db, $dbprefix, "$basedir/cache");
    print("<p><a href=showfile.$phpEx?fname=$fname>Download here</a></p>");
    print("<xmp>");
    readfile("$basedir/cache/$fname");
    print("</xmp>");
} else if (($op == 'maint_mode') || ($op == 'update_maint')) {
    if ($op == 'update_maint') {
        if (strtolower($_REQUEST['maint_set']) == 'enabled') {
            set_config('CHAT_DISABLE', 'yes');
            set_config('CHAT_DISABLE_MSG', $_REQUEST['maint_msg']);
        } else {
            set_config('CHAT_DISABLE_MSG', $_REQUEST['maint_msg']);
            $sql    = "DELETE FROM {$dbprefix}config WHERE config_name='CHAT_DISABLE'";
            $res    = $db2->sql_query($sql);
            unset($config['CHAT_DISABLE']);
        }
    }

    $msg    = '';
    if (isset($config['CHAT_DISABLE_MSG'])) {
        $msg    = $config['CHAT_DISABLE_MSG'];
    }

    if (isset($config['CHAT_DISABLE']) && ($config['CHAT_DISABLE'] == 'yes')) {
        $enabled_y  = 'CHECKED ';
        $enabled_n  = '';
    } else {
        $enabled_y  = '';
        $enabled_n  = 'CHECKED ';
    }

    $template->set_filenames(array('body' => 'admin/maint_mode.tpl'));
    $template->assign_vars(array(
        'CHAT_DISABLE_MSG'  => $msg,
        'ENABLED_Y'         => $enabled_y,
        'ENABLED_N'         => $enabled_n,
    ));
} else if (($op == 'ts_schedule') || ($op == 'update_ts_schedule')) {
    $template->set_filenames(array('body' => 'admin/ts_schedule.tpl'));

    if ($op == 'update_ts_schedule') {
        set_config('TS_SCHEDULED', strtolower($_REQUEST['ts_sched']));
        set_config('TS_DISPLAY_PMS', strtolower($_REQUEST['ts_disp_pms']));
        set_config('TS_EMAIL_LIST', strtolower($_REQUEST['ts_email_list']));
        set_config('TS_EMAIL_FROM', strtolower($_REQUEST['ts_email_from']));

        if ($config['TS_SCHEDULED'] == 'enabled' && $config['TS_EMAIL_LIST'] == '') {
            set_config('TS_SCHEDULED', 'disabled');
            $notice = "You must specify at least one email address to receive transcripts.";
            $template->assign_block_vars('switch_notice', array(
                'NOTICE'    => $notice
            ));
        } else if ($config['TS_EMAIL_FROM'] == '') {
            set_config('TS_SCHEDULED', 'disabled');
            $notice = "You must specify the sender email address generating the transcripts.";
            $template->assign_block_vars('switch_notice', array(
                'NOTICE'    => $notice
            ));
        } else if ($config['TS_SCHEDULED'] == 'enabled') {
            $notice = "Visit the Cron Settings page to schedule the email script.";
            $template->assign_block_vars('switch_notice', array(
                'NOTICE'    => $notice
            ));
        }
    }

    if (isset($config['TS_SCHEDULED']) && ($config['TS_SCHEDULED'] == 'enabled')) {
        $ts_sched_y = 'CHECKED ';
        $ts_sched_n = '';
    } else {
        $ts_sched_y = '';
        $ts_sched_n = 'CHECKED ';
    }

    if (isset($config['TS_DISPLAY_PMS']) && ($config['TS_DISPLAY_PMS'] == 'enabled')) {
        $ts_disp_pms_y  = 'CHECKED ';
        $ts_disp_pms_n  = '';
    } else {
        $ts_disp_pms_y  = '';
        $ts_disp_pms_n  = 'CHECKED ';
    }

    $ts_email_list  = '';
    if (isset($config['TS_EMAIL_LIST'])) {
        $ts_email_list  = $config['TS_EMAIL_LIST'];
    }

    $ts_email_from  = '';
    if (isset($config['TS_EMAIL_FROM'])) {
        $ts_email_from  = $config['TS_EMAIL_FROM'];
    }

    $template->assign_vars(array(
        'TS_SCHED_Y'    => $ts_sched_y,
        'TS_SCHED_N'    => $ts_sched_n,
        'TS_DISP_PMS_Y' => $ts_disp_pms_y,
        'TS_DISP_PMS_N' => $ts_disp_pms_n,
        'TS_EMAIL_LIST' => $ts_email_list,
        'TS_EMAIL_FROM' => $ts_email_from,
    ));
} else if ($op == 'ts_search') {
    $template->set_filenames(array('body' => 'admin/ts_search.tpl'));
    show_date_select(&$template, 1);
    show_date_select(&$template, 2);
    $template->assign_vars(array(
        'ROOMLIST'  =>  getRoomList(true, true)
    ));
} else if ($op == 'ts_search_results') {
    $template->set_filenames(array('body' => 'admin/ts_search_results.tpl'));

    $start  = "'{$_REQUEST['year1']}-{$_REQUEST['month1']}-{$_REQUEST['day1']} {$_REQUEST['hour1']}:{$_REQUEST['minute1']}:00'";
    $end    = "'{$_REQUEST['year2']}-{$_REQUEST['month2']}-{$_REQUEST['day2']} {$_REQUEST['hour2']}:{$_REQUEST['minute2']}:59'";

    $rid    = $_REQUEST['roomlist'];
    if ($rid == '' || $rid == -1) {
        $rid    = -1;
        $name   = 'All Rooms';
    } else {
        $room   = getRoomInfo($rid);
        $name   = $room[$name];
    }

    $filter = 'base';
    if ($_REQUEST['show_pms'] != '') {
        $filter = 'admin';
    }

    $template->assign_vars(array(
        'ROOM_NAME' => $name,
        'DATE1'     => stripslashes($start),
        'DATE2'     => stripslashes($end),
    ));

    $events = pull_transcript_events($start, $end, $rid, $filter);
    if ($events == '') {
        $events = array();
    }
    foreach ($events as $row) {
        $date_fmt   = '';
        if (isset($_REQUEST['show_timestamps']) && $_REQUEST['show_timestamps'] == 'on') {
            $date_fmt   = "[" . $row['event_date_fmt'] . "] ";
        }
    
        $room_name  = '';
        if ($rid == -1) {
            if ($row['room_id_to'] > 0) {
                $room_name  = "{$row['room_name']}: ";
            } else {
                if ($row['user_id_to'] > 0) {
                    $from_name  = getUserAliasById($row['user_id_from']);
                    $to_name    = getUserAliasById($row['user_id_to']);
                    $room_name  = "Private Message from $from_name to $to_name: ";
                } else {
                    $room_name  = 'Serverwide: ';
                }
            }
        }

        $template->assign_block_vars('events', array(
            'ROOM_NAME'     => $room_name,
            'EVENT_ID'      => $row['event_id'],
            'EVENT_DATE'    => $date_fmt,
            'EVENT_TEXT'    => stripslashes($row['event_text'])
        ));
    }
} else if (($op == 'log_config') || ($op == 'update_log_config')) {
    if (isset($_REQUEST['loglevel'])) {
        set_config('DEBUG', $_REQUEST['loglevel']);
    }

    $template->set_filenames(array('body' => 'admin/log_config.tpl'));
    foreach ($debug_levels as $name => $level) {
        $sel    = '';
        if ($config['DEBUG'] == $level) {
            $sel    = " SELECTED ";
        }
        $template->assign_block_vars('level', array(
            'NAME'      => $name,
            'LEVEL'     => $level,
            'SELECTED'  => $sel,
        ));
    }
} else {
    print("Unknown operation '$op'.<br />");
    print_r_pre($_REQUEST);
}

if ($template->files) {
    $template->pparse('body');
}

print("</td></tr>");
print("</table>");
?>
